home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: netcom.com!hester
- From: hester@netcom.com (Jim Hester)
- Subject: Function returning pointer to equivalent functions
- Message-ID: <hesterDn1E2r.K1F@netcom.com>
- Organization: NETCOM On-line Communication Services (408 261-4700 guest)
- Distribution: usa
- Date: Mon, 19 Feb 1996 18:59:15 GMT
- Sender: hester@netcom9.netcom.com
-
-
- I want a group of functions that each can return a pointer to any other
- function in that group. I can't find any direct way to declare the
- function's type since the return type ends up in a "recursive" definition
- loop. I'd prefer to avoid dirty type changes like using void pointers.
-
- The best that I have done is to envelope the functions in a class and
- return a pointer to the class (example below). Context: The purpose
- of these functions is to run an automaton. The main() function below
- demonstrates it's intended control (except the input char, which SHOULD
- be pulled from an input stream).
-
- If states are numbered (as in my unimaginative example below), it's easy
- to have the functions return indices in an array containing pointers to
- all of the functions. That's the method I've used in the past. The
- only problem is that I can't use descriptive state names without going
- into manually #defining constants for function locations.
-
- My main question is:
- Can anyone show me a way of directly declaring the functions to return the
- pointer I want?
-
- If not, other suggestions?
-
- If not, can anybody improve what I have below? The best improvement I
- can think of is a casting operator from FnEnvelope to pFnEnvelope that
- would let me forget about adding the '&'s where I need them below.
- I tried (in public): operator StateType() {return this;}
- but the compiler didn't like it.
-
- #include <iostream.h>
-
- class FnEnvelope;
-
- typedef StateType (*pStateFn)(char);
-
- class FnEnvelope
- {
- public:
- FnEnvelope (StateType (*i_F)(char)) : F(i_F) { }
- StateType Run(char c) { return (*F)(c); }
-
- private:
- StateType (*F)(char);
- };
-
- StateType State1Fn(char); FnEnvelope State1(State1Fn);
- StateType State2Fn(char); FnEnvelope State2(State2Fn);
- FnEnvelope StateQuit(NULL);
-
- StateType State1Fn(char c)
- {
- cout << "this is state1: " << c << endl; // testing
- switch (c)
- {
- case 'e':
- return &StateQuit;
- default:
- return &State2;
- }
- }
-
- StateType State2Fn(char c)
- {
- cout << "this is state2: " << c << endl; // testing
- switch (c)
- {
- case 'e':
- return &StateQuit;
- default:
- return &State1;
- }
- }
-
- void main(void)
- {
- StateType State;
- char c = 'a';
- for ( State = &State1 ; State != &StateQuit ; State = State->Run(c++) );
- }
-